<?php

require_once LIBRARIES_ENTITIES_DATABASE;
require_once LIBRARIES_ENTITIES_USERS;
require_once LIBRARIES_ENTITIES_GROUPS;
require_once LIBRARIES_ENTITIES_GROUPUSERS;

require_once LIBRARIES_TOOLS_UTILITY;
require_once LIBRARIES_TOOLS_XTEMPLATE;
require_once LIBRARIES_TOOLS_PAGERBACKEND;

class UserController {

    public function invoke() {

        // function list
        $groupFunctions = $_SESSION['groupFunctions'];

        // directory path
        $dir = dirname(__FILE__);

        $view = '';
        if (isset($_GET['view'])) {
            $view = $_GET['view'];
        }

        $action = '';
        if (isset($_POST['hdAction'])) {
            $action = $_POST['hdAction'];
        }



        $task = '';
        if (isset($_GET['task'])) {
            $task = $_GET['task'];
        }


        $rowToView = 10;
        if (isset($_POST["limit"])) {
            $rowToView = $_POST["limit"];
        }


        switch ($action) {
            case "publish":
                $values = $_POST["cid"];
                $result = $this->updateStatus($values, true);
                break;
            case "unpublish":
                $values = $_POST["cid"];
                $result = $this->updateStatus($values, false);
                break;
            case 'remove':
                $values = $_POST["cid"];
                $result = $this->deleteUser($values);
                if ($result == OK) {
                    Utility::messageBox('Xóa thành công');
                }
                break;
            case 'add':
            case 'addAndExit':

                $userName = $_POST['txtUserName'];
                // check the existence of username
                $already = $this->getUserByUserName($userName);
                if ($already == null) {
                    $fullName = $_POST['txtFullName'];
                    $email = $_POST['txtEmail'];
                    $groupID = $_POST['slGroupID'];
                    $password = md5($_POST['txtPassword']);
                    $status = $_POST['rdoStatus'];

                    $result = $this->addUser($userName, $fullName, $email, $password, $status, $groupID);

                    if ($result == OK) {
                        if ($action == 'add') {
                            Utility::messageBox('Thêm thành công');
                        } else {
                            Utility::redirect(".?com=com_user&task=view");
                        }
                    }
                } else {
                    Utility::messageBox('Tên đăng nhập này đã có rồi, vui lòng chọn tên khác');
                }
                break;
            case 'edit':
            case 'editAndExit':

                $userID = $_POST['hdID'];
                $fullName = $_POST['txtFullName'];
                $email = $_POST['txtEmail'];
                $groupID = $_POST['slGroupID'];

                if (trim($_POST['txtPassword']) != '') {
                    $password = md5($_POST['txtPassword']);
                } else {
                    $password = $_POST['hdOldPassword'];
                }
                $status = $_POST['rdoStatus'];


                $result = $this->updateUser($userID, $fullName, $password, $email, $groupID, $status);

                if ($result == OK) {
                    if ($action == 'edit') {
                        Utility::messageBox('Sửa thành công');
                    } else {
                        Utility::redirect(".?com=com_user&task=view");
                    }
                }
                break;
            case 'cancel':
                Utility::redirect(".?com=com_user&task=view");
                break;
        }






        if ($task == 'view') {

            // check view permission
            if (Utility::checkPermission('view', $groupFunctions, USER_MANAGEMENT)) {

                $viewFile = $dir . '/views/user_list.html';
                $xtemplate = new XTemplate($viewFile);

                // CHECK PERMISSION
                // check add button
                if (Utility::checkPermission('add', $groupFunctions, USER_MANAGEMENT)) {
                    $xtemplate->parse('main.add_button');
                }
                // check delete button
                if (Utility::checkPermission('delete', $groupFunctions, USER_MANAGEMENT)) {
                    $xtemplate->parse('main.delete_button');
                }
                // check enable button
                if (Utility::checkPermission('enable', $groupFunctions, USER_MANAGEMENT)) {
                    $xtemplate->parse('main.enable_button');
                }
                // check disable button
                if (Utility::checkPermission('disable', $groupFunctions, USER_MANAGEMENT)) {
                    $xtemplate->parse('main.disable_button');
                }


                $indexCheckBox = 1;

                $rurrentPage = 1;
                if (isset($_POST["page"])) {
                    $rurrentPage = $_POST["page"];
                }


                // chỉ mục (số thứ tự của bài viết) bài viết
                $index = 1;

                $users = $this->getUserList();

                $pager = PagerBackEnd::getPagerData(count($users), $rowToView, $rurrentPage);


                if ($users != null) {

                    $indexCheckBox = 1;


                    foreach ($users as $user) {

                        if ($index > $pager->offset && $index <= $pager->limit) {

                            // kiểm tra user đó nếu là quản trị cấp cao thì không hiển thị
                            $groupUser = $this->getGroupUserByUserID($user->getID());

                            // vì hiện thời mỗi user chỉ thuộc 1 group nên ta lấy vị trị mảng là 0
                            if ($groupUser[0]->getGroupID() != 1) {


                                // danh sách nhóm mà người dùng thuộc về
                                $group = '';
                                $groupUsers = $this->getGroupListByUserID($user->getID());
                                for ($y = 0; $y < count($groupUsers); $y++) {
                                    if ($y == 0) {
                                        $group .= $groupUsers[$y]->getGroup()->getName();
                                    } else {
                                        $group .= ', ' . $groupUsers[$y]->getGroup()->getName();
                                    }
                                }




                                $xtemplate->assign('INDEX', $index);
                                $xtemplate->assign('INDEX_CHECKBOX', $indexCheckBox);

                                $xtemplate->assign('ID', $user->getID());
                                $xtemplate->assign('USERNAME', $user->getUserName());
                                $xtemplate->assign('FULLNAME', $user->getFullname());
                                $xtemplate->assign('EMAIL', $user->getEmail());
                                $xtemplate->assign('GROUP', $group);


                                // check update permission                            
                                if (Utility::checkPermission('update', $groupFunctions, USER_MANAGEMENT)) {
                                    $xtemplate->parse('main.user_list.update_button');
                                } else {
                                    $xtemplate->parse('main.user_list.update_button_disable');
                                }


                                // status
                                if ($user->getStatus() == 1) {
                                    $xtemplate->assign('STATUS_ACTION', 'unpublish');
                                    $xtemplate->assign('STATUS_IMAGE', 'publish_g.png');
                                } else {
                                    $xtemplate->assign('STATUS_ACTION', 'publish');
                                    $xtemplate->assign('STATUS_IMAGE', 'publish_r.png');
                                }


                                $xtemplate->parse('main.user_list');

                                $indexCheckBox++;
                            }
                        }
                        $index++;
                    }
                }

                $xtemplate->assign('LIMIT_LIST', Utility::getLimitList($rowToView));
                $xtemplate->assign('ROW_TO_VIEW', $rowToView);
                $xtemplate->assign('CURRENT_PAGE', $rurrentPage);
                $xtemplate->assign('AMOUNT_OF_PAGE', $pager->numPages);
                $xtemplate->assign('PAGING_HTML', $pager->paging);
                $xtemplate->parse('main');
                $xtemplate->out('main');
            } else {
                echo ERROR_PERMISSION;
            }
        } else if ($task == 'add') {

            // check add permission
            if (Utility::checkPermission('add', $groupFunctions, USER_MANAGEMENT)) {
                $xtemplate = new XTemplate($dir . '/views/user_add.html');

                $this->printGroupList($xtemplate);

                $xtemplate->assign('TODAY', date('d/m/Y'));
                $xtemplate->assign('UPLOAD_FOLDER', UPLOAD_FOLDER);
                $xtemplate->parse('main');
                $xtemplate->out('main');
            } else {
                echo ERROR_PERMISSION;
            }
        } else if ($task == 'edit') {

            // check add permission
            if (Utility::checkPermission('update', $groupFunctions, USER_MANAGEMENT)) {
                $ID = '';
                if (isset($_GET['ID'])) {
                    $ID = $_GET['ID'];
                }

                $user = $this->getUserByID($ID);

                if ($user != null) {

                    $viewFile = $dir . '/views/user_edit.html';
                    $xtemplate = new XTemplate($viewFile);

                    // groups of user
                    $groupsOfUser = $this->getGroupListByUserID($user->getID());

                    $xtemplate->assign('USER_ID', $user->getID());
                    $xtemplate->assign('USER_NAME', $user->getUserName());
                    $xtemplate->assign('FULL_NAME', $user->getFullname());
                    $xtemplate->assign('EMAIL', $user->getEmail());
                    $xtemplate->assign('PASSWORD', $user->getPassword());
                    $xtemplate->assign('GROUP_ID', $groupsOfUser[0]->getGroupID());



                    // show group list
                    $this->printGroupList($xtemplate, $groupsOfUser[0]->getGroupID());





                    if ($user->getStatus() == 1) {
                        $xtemplate->parse('main.status_true');
                    } else {
                        $xtemplate->parse('main.status_false');
                    }

                    $xtemplate->parse('main');
                    $xtemplate->out('main');
                } else {
                    Utility::redirect('.?com=com_user&task=view');
                }
            } else {
                echo ERROR_PERMISSION;
            }
        }
    }

    private function getUserList() {
        $db = new Database();
        try {
            $user = new Users();
            $result = $user->getList($db);
            $db->submitChanges();
            return $result;
        } catch (Exception $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function getGroupList() {
        $db = new Database();
        try {
            $group = new Groups();
            $result = $group->getList($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function getGroupUserByUserID($userID) {
        $db = new Database();
        try {
            $groupUser = new GroupUsers();
            $groupUser->setUserID($userID);
            $result = $groupUser->getByUserID($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function printGroupList($xtemplate, $selectedID = null) {

        $groups = $this->getGroupList();

        foreach ($groups as $group) {
            $xtemplate->assign('GROUP_NAME', $group->getName());
            $xtemplate->assign('GROUP_ID', $group->getID());

            if ($group->getVisable() == 1) {
                if ($selectedID != null) {
                    if ($selectedID == $group->getID()) {
                        $xtemplate->assign('SELECTED', 'selected');
                    } else {
                        $xtemplate->assign('SELECTED', '');
                    }
                } else {
                    if (isset($_POST['slGroupID'])) {
                        if ($_POST['slGroupID'] == $group->getID()) {
                            $xtemplate->assign('SELECTED', 'selected');
                        } else {
                            $xtemplate->assign('SELECTED', '');
                        }
                    } else if (isset($_GET['groupID'])) {

                        if ($_GET['groupID'] == $group->getID()) {
                            $xtemplate->assign('SELECTED', 'selected');
                        } else {
                            $xtemplate->assign('SELECTED', '');
                        }
                    } else {
                        $xtemplate->assign('SELECTED_CATEGORY', '');
                    }
                }
                $xtemplate->parse('main.group_list');
            }
        }
    }

    private function addUser($userName, $fullName, $email, $password, $status, $groupID) {
        $db = new Database();
        try {
            $user = new Users();
            $user->setUserName($userName);
            $user->setFullname($fullName);
            $user->setEmail($email);
            $user->setPassword($password);
            $user->setStatus($status);
            $userID = $user->add($db);


            $groupUser = new GroupUsers();
            $groupUser->setUserID($userID);
            $groupUser->setGroupID($groupID);
            $groupUser->add($db);

            $db->submitChanges();

            return OK;
        } catch (PDOException $ex) {
            echo $ex->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function deleteUser($values) {
        $db = new Database();
        try {
            for ($i = 0; $i < count($values); $i++) {
                $user = new Users();
                $user->setID($values[$i]);
                $user->delete($db);
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $ex) {
            echo $ex->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function updateUser($userID, $fullName, $password, $email, $groupID, $status) {
        $db = new Database();
        try {
            $user = new Users();
            $user->setID($userID);
            $user->setFullname($fullName);
            $user->setEmail($email);
            $user->setPassword($password);
            $user->setStatus($status);
            $user->update($db);


            $groupUserForDelete = new GroupUsers();
            $groupUserForDelete->setUserID($userID);
            $groupUserForDelete->deleteByUserID($db);

            $groupUserForAdd = new GroupUsers();
            $groupUserForAdd->setUserID($userID);
            $groupUserForAdd->setGroupID($groupID);
            $groupUserForAdd->add($db);

            $db->submitChanges();

            return OK;
        } catch (PDOException $ex) {
            echo $ex->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function getUserByID($userID) {
        $db = new Database();
        try {
            $user = new Users();
            $user->setID($userID);
            $result = $user->getByID($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $ex) {
            echo $ex->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function getUserByUserName($userName) {
        $db = new Database();
        try {
            $user = new Users();
            $user->setUserName($userName);
            $result = $user->getByUserName($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $ex) {
            echo $ex->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function updateStatus($values, $status) {
        $db = new Database();
        try {
            for ($i = 0; $i < count($values); $i++) {
                $user = new Users();
                $user->setStatus($status);
                $user->setID($values[$i]);
                $user->updateStatus($db);
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $ex) {
            echo $ex->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function getGroupListByUserID($userID) {
        $db = new Database();
        try {
            $groupUser = new GroupUsers();
            $groupUser->setUserID($userID);

            $result = $groupUser->getListByUserID($db);
            $db->submitChanges();
            return $result;
        } catch (Exception $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

}

?>
